package com.ems.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 初始化线程池
 * Executor：执行器
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorUtil {

    private int corePoolSize = 10;//线程池维护线程的最少数量
    private int maxPoolSize = 50;//线程池维护线程的最大数量
    private int queueCapacity = 20; //缓存队列
    private int keepAlive = 120;//允许的空闲时间

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor () {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor ();
        threadPoolTaskExecutor.setCorePoolSize ( corePoolSize );
        threadPoolTaskExecutor.setMaxPoolSize ( maxPoolSize );
        threadPoolTaskExecutor.setQueueCapacity ( queueCapacity );
        threadPoolTaskExecutor.setThreadNamePrefix ( "threadExecutor-" );
        threadPoolTaskExecutor.setRejectedExecutionHandler ( new ThreadPoolExecutor.CallerRunsPolicy () ); //对拒绝task的处理策略
        threadPoolTaskExecutor.setKeepAliveSeconds ( keepAlive );
        threadPoolTaskExecutor.initialize ();
        return threadPoolTaskExecutor;
    }

}
